<?php
namespace backend\models\activeRecords;

use common\libs\Constants;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%spread_info}}".
 *
 * @property string $id 自增id
 * @property string $guild_sign 所属公会标识
 * @property string $spread_key_1 推广类型
 * @property string $spread_key_2 所属员工
 * @property string $spread_url 推广链接
 * @property string $spread_surl 短链接
 * @property int $game_id 游戏ID
 * @property int $server_id 区服ID
 */
class SpreadInfo extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%spread_info}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['game_id', 'server_id'], 'required'],
            [['game_id', 'server_id'], 'integer'],
            [['guild_sign', 'spread_key_1', 'spread_key_2'], 'string', 'max' => 50],
            [['spread_url', 'spread_surl'], 'string', 'max' => 1000],
            [['game_id'],'validateGameUrl']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '自增id'),
            'guild_sign' => Yii::t('app', '所属公会标识'),
            'spread_key_1' => Yii::t('app', '推广类型'),
            'spread_key_2' => Yii::t('app', '所属员工'),
            'spread_url' => Yii::t('app', '推广链接'),
            'spread_surl' => Yii::t('app', '短链接'),
            'game_id' => Yii::t('app', '游戏ID'),
            'server_id' => Yii::t('app', '区服ID'),
        ];
    }

    public function beforeSave($insert)
    {
        $spreadUrl = SpreadUrl::findOne(['game_id'=>$this->game_id]);
        $this->guild_sign = Yii::$app->user->getIdentity()->parent;
        $this->spread_key_1 = Constants::ANCHOR;
        $this->spread_key_2 = Yii::$app->user->getIdentity()->position;
        $this->spread_url = empty($spreadUrl->game_url)?"":$spreadUrl->game_url."?sp=".$this->spread_key_1
            .'&server_id='.$this->server_id
            .'&uid='.$this->spread_key_2
            .'&suid='.$this->guild_sign;
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public function getGame(){
        return $this->hasOne(TGame::className(),['game_id'=>'game_id']);
    }

    public function getServer(){
        return $this->hasOne(TServer::className(),['server_id'=>'server_id']);
    }

    public function validateGameUrl($attributes,$params){
        if(!$this->hasErrors()){
            $spreadUrl = SpreadUrl::findOne(['game_id'=>$this->game_id]);
            if(empty($spreadUrl)){
                $this->addError($attributes,'请先添加游戏的基础推广链接');
            }
        }
    }


}
